package main

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"ztchat/global"
)

type RecvMessage struct {
	Type int    `json:"type"`
	Msg  string `json:"msg"`
	WxID string `json:"wx_id"`
	PID  uint   `json:"pid,omitempty"`
	Port uint   `json:"port"`
}

func listenForDLLSignal() {
	http.HandleFunc("/msg", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Support POST method only", http.StatusMethodNotAllowed)
			return
		}

		body, err := io.ReadAll(r.Body)

		if err != nil {
			http.Error(w, "Failed to read request body", http.StatusInternalServerError)
			return
		}

		var recv RecvMessage

		if err := json.Unmarshal(body, &recv); err != nil {
			http.Error(w, "Invalid JSON format", http.StatusBadRequest)
			return
		}

		if recv.Msg, err = global.GbkToUtf8([]byte(recv.Msg)); err != nil {
			log.Printf("Failed to convert Msg from GBK to UTF-8: %v\n", err)
			http.Error(w, "Encoding error", http.StatusInternalServerError)
			return
		}

		switch recv.Type {
		case 1000:
			log.Printf(
				"Received type 1000 message: %s, from WeChat ID: %s, PID: %d, Port: %d\n",
				recv.Msg,
				recv.WxID,
				recv.PID,
				recv.Port,
			)
			w.Write([]byte("Processed type 1000 message"))
			os.Exit(0)

		case 999:
			log.Printf(
				"Received type 999 message: %s, from WeChat ID: %s, Port: %d\n",
				recv.Msg,
				recv.WxID,
				recv.Port,
			)
			w.Write([]byte("Processed type 999 message"))
			os.Exit(0)

		default:
			log.Printf("Ignored message of type: %d\n", recv.Type)
			w.WriteHeader(http.StatusNoContent)
		}
	})

	log.Println("Listening on port 9000 for DLL signal...")

	if err := http.ListenAndServe(":9000", nil); err != nil {
		log.Fatal("Error starting listen server: ", err)
	}
}
